package com.example.telesys.test;

import com.example.telesys.RocketMQTransactionEntity.TxLog;
import com.example.telesys.mapper.SupplierMapper;
import com.example.telesys.mapper.TxLogMapper;
import com.example.telesys.pojo.Supplier;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
public class SendTransactionMessage {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private TxLogMapper txLogMapper;


    /**
     * 利用RocketMQ发送半事务消息
     */
    public TransactionSendResult createSupplierBefore(Supplier supplier){
        String txLogId = UUID.randomUUID().toString();
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "tx_producer_group",
                "tx_topic",
                MessageBuilder.withPayload(supplier).setHeader("txLogId", txLogId).build(),
                supplier
        );
        return transactionSendResult;
    }

    /**
     * 本地事务
     * @param supplier
     */
    @Transactional
    public void createSupplier(String txLogId, Supplier supplier){
        //保存供应商数据
        supplierMapper.insert(supplier);
        //记录事务日志
        TxLog txLog = new TxLog();
        txLog.setTxId(txLogId);
        txLog.setDate(new Date());
        txLogMapper.insert(txLog);
    }
}
